<template>
    <div class="contentmain">
    
        <el-form :model="f" status-icon label-width="150px" class="demo-ruleForm" :rules="goodsRules" style="width:70%">
    
            <el-form-item label="商品名称" prop="name">
                <el-input type="text" v-model="f.name"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" class="is-required">
                <el-select v-model="f.cateId" placeholder="请选择">
                    <el-option v-for="item in opt" :key="item.gcId" :label="item.gcName" :value="item.gcId">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="标签">
                <el-input type="text" v-model="f.tag"></el-input>
            </el-form-item>
            <GoodValue :pList="plist" @pList-change="pListChange">
            </GoodValue>
            <el-form-item label="运费">
                <el-input type="number" value="4" style="width:20%" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="配送方式">
                <el-select v-model="deliverytype" placeholder="请选择配送方式">
                    <el-option v-for="i in opt3" :key="i.vlaue" :label="i.label" :value="i.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="拼团配送方式">
                <el-select v-model="ptDeliverytype" placeholder="请选择配送方式">
                    <el-option v-for="i in opt3" :key="i.vlaue" :label="i.label" :value="i.value"></el-option>
                </el-select>
            </el-form-item>
            <!-- 相关参数设置 -->
    
    
<!--     
            <el-form-item label="商品价格" prop="price">
    
                <el-input type="number" v-model="f.price" style="width:20%"></el-input>
    
            </el-form-item>
    
            <el-form-item label="商品原价" prop="oldPrice">
    
                <el-input type="number" v-model="f.oldPrice" style="width:20%"></el-input>
    
            </el-form-item> -->
    
            <el-form-item label="单位" prop="spec">
    
                <el-input type="text" v-model="f.spec" style="width:20%"></el-input>
    
            </el-form-item>
    
            <el-form-item label="线上销售规格" class="is-required">
    
                <GoodCount :cList="clist" @cList-change="cListChange">

                </GoodCount>
    
            </el-form-item>
    
            <el-form-item label="是否上架" class="is-required">
    
                <el-radio-group v-model="ra">
    
                    <el-radio :label='1'>上架</el-radio>
    
                    <el-radio :label='0'>下架</el-radio>
    
                </el-radio-group>
    
            </el-form-item>
    
            <!-- 图片上传 -->
    
            <el-form-item label="商品图">
    
                <el-upload drag action="http://up-z0.qiniu.com" :data="uploadData" :file-list="fileDetailUploadList" :on-success="handleDetailUploadSuccess" :on-remove="handleDetailRemove" :on-error="handleUploadError" :before-upload="handleBeforUpload" list-type="picture-card">
    
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    
                    <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
    
                </el-upload>
    
            </el-form-item>
    
            <el-form-item label="商品缩略图" style="margin-top:20px">
    
                <el-upload drag action="http://up-z0.qiniu.com" :data="uploadData" :file-list="fileSmallUploadList" :on-success="handleSmallUploadSuccess" :on-remove="handleSmallRemove" :on-error="handleUploadError" :before-upload="handleBeforUpload" list-type="picture-card">
    
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    
                    <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
    
                </el-upload>
    
            </el-form-item>
    
            <!-- 富文本编辑器 -->
    
            <el-form-item label="商品详情">
    
                <editor ref="myTextEditor" v-model="f.detail" :options="editorOption" @blur="onEditorBlur($event)" @focus="onEditorFocus($event)" @ready="onEditorReady($event)">
    
                    <div id="toolbar" slot="toolbar">
    
                        <span class="ql-formats"><button type="button" class="ql-bold"></button></span>
    
                        <span class="ql-formats"><button type="button" class="ql-italic"></button></span>
    
                        <span class="ql-formats"><button type="button" class="ql-blockquote"></button></span>
    
                        <span class="ql-formats"><button type="button" class="ql-list" value="ordered"></button></span>
    
                        <span class="ql-formats"><button type="button" class="ql-list" value="bullet"></button></span>
    
                        <span class="ql-formats"><button type="button" class="ql-link"></button></span>
    
                        <span class="ql-formats"><button type="button" class="ql-video"></button></span>
    
                        <span class="ql-formats">
    
                            <el-upload
    
                                    class="upload-demo"
    
                                    action="http://up-z0.qiniu.com"
    
                                    :data="uploadData"
    
                                    :file-list="fileTextUploadList"
    
                                    :on-success="handleTextUploadSuccess"
    
                                    :on-error="handleUploadError"
    
                                    :before-upload="handleBeforUpload"
    
                            >
    
                                <button type="button" style="outline:none;margin-top: 12px">
    
                                    <svg viewBox="0 0 18 18"> <rect class="ql-stroke" height="10" width="12" x="3" y="4"></rect> <circle class="ql-fill" cx="6" cy="7" r="1"></circle> <polyline class="ql-even ql-fill" points="5 12 5 11 7 9 8 10 11 7 13 9 13 12 5 12"></polyline> </svg>
    
                                </button>
    
                            </el-upload>
    
                        </span>
    
                    </div>
    
                </editor>
    
    
    
            </el-form-item>
    
            <el-form-item>
    
                <el-button type="primary" @click="check">提交</el-button>
    
            </el-form-item>
    
    
    
        </el-form>
    
    
    
    </div>
</template>
<script>
    import editor from 'components/quille'
    
    import GoodValue from 'components/GoodPushItem/GoodValue'
    
    import GoodCount from 'components/GoodPushItem/GoodCount'
    
    import qs from 'qs'
    
    export default {
    
        data() { //验证
    
            var checkPrice = (rule, value, callback) => {
    
                if (!value) {
    
                    return callback(new Error('请填写商品价格'));
    
                }
    
                setTimeout(() => {
    
                    if (!Number(value)) {
    
                        callback(new Error('请填写数字'));
    
                    } else {
    
                        if (value <= 0) {
    
                            callback(new Error('商品价格必须大于0'));
    
                        } else {
    
                            callback();
    
                        }
    
                    }
    
                }, 500);
    
            };
    
            return {
    
                f: {
                    cateId: '',
                    deliveryPrice:8,
                },
                deliverytype:0,
                ptDeliverytype:2,
                opt3: [{
                    value: 0,
                    label: "全部"
                }, {
                    value: 2,
                    label: "自提"
                }],
                goodsRules: { //验证
    
                    name: [{
    
                        required: true,
    
                        message: '请填写商品名称',
    
                        trigger: 'blur'
    
                    }],
    
                    cateId: [{
    
                        required: true,
    
                        message: '请选择商品分类',
    
                        trigger: 'change'
    
                    }],    
                    spec: [{
    
                        required: true,
    
                        message: '请填写商品规格',
    
                        trigger: 'blur'
    
                    }]
    
                },
    
                paramsList: {},
    
                content: '',
    
                editorOption: {
    
                    modules: {
    
                        toolbar: '#toolbar'
    
                    }
    
                },
                opt: [],
                opt2: [],
                val2: '',
                input4: '',
                fileDetailUploadList: [],
                fileSmallUploadList: [],
                fileTextUploadList: [],
                ra: 0,
                fa: 1,
                plist: [{
                    key: '产地',
                    value: ''
                }, {
                    key: '包装',
                    value: ''
                }],
                image: "",
                thumImage: "",
                uploadData: {
                    key: '',
                    token: ''
                },
                goodid: -1,
                clist: [{
                    count: '',
                    price:'',
                    oldPrice:'',
                    ptType:'',
                    ptPrice:''
                }],
                goodcount: {}
    
            }
    
        },
    
        components: { //组件
    
            editor,
    
            GoodValue,
    
            GoodCount
    
        },
    
        computed: { //返回富文本编辑内容
    
            editor() {
    
                return this.$refs.myTextEditor.quill
    
            }
    
        },
    
        activated() { //因为使用watch监听路由的效果不是很好,所以使用了这个生命周期
    
            //监听当前URL
    
            //如果包含'?'执行截取内容,提交到接口查询单个id的商品
    
            //如果不包含,清空所有输入框里的内容
    
            var iv = window.location.href.toString()
    
            if (iv.indexOf('?') == -1) {
    
                this.f = {}
                this.deliverytype=0
                this.ptDeliverytype=2
                this.fileDetailUploadList = []
                this.fileSmallUploadList = []
                this.fileTextUploadList = []
                this.ra = 0
                this.plist = [{
                    key: '产地',
                    value: ''
                }, {
                    key: '包装',
                    value: ''
                }]
                this.goodid = -1
                return
            } else {
                var str = iv.split('?')
                var id = str[1].split('=')
                this.goodid = parseInt(id[1])
                this.getupdatedata(parseInt(id[1]))
            }
        },
    
        deactivated() {
    
            //当前页面不活动的时候清空所有
    
            this.f = {}
    
            this.fileDetailUploadList = []
    
            this.fileSmallUploadList = []
    
            this.fileTextUploadList = []
    
            this.clist = [{
                count: '',
                price:'',
                oldPrice:'',
                ptType:'',
                ptPrice:''
            }]
    
            this.goodid = -1
    
        },
    
        methods: {
    
            validateParams() {
                for (var i of this.paramsList) {
                    if (i.key == '' || i.val == '') {
                        return false
                    }
                }
                return true
            },
            validateCount() {
                for (var i of this.goodcount) {
                    if (i.count== ''||i.price== ''||i.oldPrice== ''||i.ptType== ''||i.ptPrice== '') {
                        return false
                    }
                    if( parseFloat(i.count)<0||parseFloat(i.price)<0||parseFloat(i.oldPrice)<0||parseFloat(i.ptType)<0||parseFloat(i.ptPrice)<0){
                        return false
                    }
                }
                return true
            },
            check() { //检查验证,以及上传保存,上传时有个判断goodid,如果存在,带id作为修改上传,如果不存在,直接上传
    
                var _this = this
    
                var pp = new URLSearchParams()
    
                if (this.goodid != -1) {
    
                    pp.append("goodsId", this.goodid)
    
                }
    
                if (this.f.name == '') {
    
                    this.$message.info('商品名称不能为空')
    
                    return
    
                }
    
                pp.append("name", this.f.name)
    
                pp.append("cateId", this.f.cateId)
    
                pp.append("tag", this.f.tag)
    
                if (!this.validateParams()) {
    
                    this.$message.error('请将商品参数填写完整')
    
                    return false
    
                }
    
                pp.append("param", JSON.stringify(this.paramsList))
    
                pp.append("stockNum", 0)
    
                pp.append("spec", this.f.spec)
    
                pp.append("image", this.fileDetailUploadList.length > 0 ? this.fileDetailUploadList[0].url : '')
    
                pp.append('deliverytype',this.deliverytype)

                pp.append('ptDeliverytype',this.ptDeliverytype)

                pp.append('deliveryPrice',4)
    
                pp.append("thumImage", this.fileSmallUploadList.length > 0 ? this.fileSmallUploadList[0].url : '')
    
                pp.append("status", this.ra)
    
                pp.append("detail", this.f.detail)
    
                if (!this.validateCount()) {
    
                    this.$message.error('线上销售规格信息不能为空或小于0')
    
                    return
    
                }
    
                pp.append('specCount', JSON.stringify(this.goodcount))
                
    
                if (this.goodid == -1) {

    
                    axios.post('/saveXcxGoods.do', pp).then(r => {
                        
                        // console.log("新增商品",r)
    
                        if (r.data.code == 200) {
                            var xcxGoodSpecList=[]

                            for(var i=0;i<_this.goodcount.length;i++){
                                var obj={}
                                obj.count=_this.goodcount[i].count
                                obj.price=_this.goodcount[i].price
                                obj.oldPrice=_this.goodcount[i].oldPrice
                                obj.goodId=r.data.response.goodId
                                obj.spec=_this.f.spec
                                obj.ptPrice=_this.goodcount[i].ptPrice
                                obj.ptType=_this.goodcount[i].ptType
                                obj.type=1
                                xcxGoodSpecList.push(obj)
                            }
                            axios.post('/saveShopPriceByXcxGoodSpec.do?', xcxGoodSpecList, {headers: {'Content-Type': 'application/json;charset=utf-8'}})
                            axios.post('/saveXcxGoodSpec.do?', xcxGoodSpecList, {headers: {'Content-Type': 'application/json;charset=utf-8'}}).then(r=>{
                                if(r.data.code==200){
                                    _this.$message({
                                        message: '添加成功',
                                        type: 'success'
                                    })
                                    _this.$router.push('/GoodList')
                                    _this.f = {}
                                    _this.fileDetailUploadList = []
                                    _this.fileSmallUploadList = []
                                    _this.fileTextUploadList = []
                                    _this.goodid = -1
                                     
                                }else{
                                    _this.$message.error(r.data.message)
                                }
                            })
                        } else {
    
                            _this.$message.error(r.data.message)
    
                        }
    
                    })
    
                } else {
                    axios.get('/updateXcxGoodsInfoById.do', {
    
                        params: pp
    
                    }).then(r => {
                        if (r.data.code == 200) {

                            var xcxGoodSpecList=[]

                            for(var i=0;i<_this.goodcount.length;i++){
                                var obj={}
                                obj.count=_this.goodcount[i].count
                                obj.price=_this.goodcount[i].price
                                obj.oldPrice=_this.goodcount[i].oldPrice
                                obj.goodId=_this.goodid
                                obj.spec=_this.f.spec
                                obj.ptPrice=_this.goodcount[i].ptPrice
                                obj.ptType=_this.goodcount[i].ptType
                                obj.type=2
                                xcxGoodSpecList.push(obj)
                            }

                            axios.post('/saveXcxGoodSpec.do?', xcxGoodSpecList, {headers: {'Content-Type': 'application/json;charset=utf-8'}}).then(r=>{
                                if(r.data.code==200){
                                    _this.$message({
                                        message: '修改成功',
                                        type: 'success'
                                    })
                                    _this.$router.push('/GoodList')
                                    _this.f = {}
                                    _this.fileDetailUploadList = []
                                    _this.fileSmallUploadList = []
                                    _this.fileTextUploadList = []
                                    _this.goodid = -1
                                     
                                }else{
                                    _this.$message.error(r.data.message)
                                }
                            })
    
                        } else {
    
                            _this.$message.error(r.data.message)
    
                        }
    
                    })
    
                }
    
    
    
            },
    
            checkURL() {
    
                var iv = window.location.href
    
                // console.log(iv)
    
                if (iv.indexOf('?') == -1) {
    
                    return
    
                } else {
    
                    var str = iv.split('?')
    
                    var id = str[1].split('=')
    
                    // console.log(iv,id)
    
                    this.getupdatedata(parseInt(id[1]))
    
                }
    
            },
    
            handleSmallUploadSuccess(response, file, fileList) { //图片上传成功后,将值返回给我,赋值到fileSmallUploadList
    
                // console.log(response,file,fileList)
    
                var newFile = {
    
                    name: file.name,
    
                    url: window.qiniuHost + response.key
    
                }
    
                this.fileSmallUploadList = []
    
                this.fileSmallUploadList.push(newFile)
    
                // console.log(this.fileDetailUploadList)
    
            },
    
            qiniuyunup(_vm, file, rule) { //图片上传
    
                const isJPG = file.type === 'image/jpeg'
    
                const isPNG = file.type === 'image/png'
    
                const isFitSize = rule.maxSize ? file.size / 1024 / 1024 < rule.maxSize : 'undefined';
    
                if (rule.isJPG || rule.isPNG) {
    
                    if (!isJPG && !isPNG) {
    
                        _vm.$message.error('图片只能是 JPG/PNG 格式!');
    
                        return false
    
                    }
    
                }
    
                if (isFitSize != 'undefined' && !isFitSize) {
    
                    _vm.$message.error('大小不能超过 ' + rule.maxSize + 'MB!');
    
                    return false
    
                }
    
            },
    
            handleDetailRemove() { //图片清空
    
                this.fileDetailUploadList = []
    
            },
    
            handleTextRemove() { //图片清空
    
                this.fileTextUploadList = []
    
            },
    
            handleSmallRemove() { //图片清空
    
                this.fileSmallUploadList = []
    
            },
    
            handleDetailUploadSuccess(response, file, fileList) { //图片上传成功
    
                var newFile = {
    
                    name: file.name,
    
                    url: window.qiniuHost + response.key
    
                }
    
                this.fileDetailUploadList = []
    
                this.fileDetailUploadList.push(newFile)
    
            },
    
            handleUploadError(error, file, fileList) { //图片上传失败
    
                const _this = this
    
                _this.$message.error('上传失败')
    
            },
    
            handleBeforUpload(file) { //图片上传前验证
    
                // console.log("file",file)
    
                const _this = this
    
                let rule = {
    
                    isJPG: true,
    
                    isPNG: true,
    
                    maxSize: 2
    
                }
    
                var suffix = file.name.split('.')
    
                this.uploadData.key = new Date().getTime() + '.' + suffix[1]
    
                this.uploadData.token = this.$store.state.qiniuToken
    
                return this.qiniuyunup(_this, file, rule)
    
            },
    
            handleTextUploadSuccess(response, file, fileList) { //图片上传成功
    
                var newFile = {
    
                    name: file.name,
    
                    url: window.qiniuHost + response.key
    
                }
    
                this.fileTextUploadList = []
    
                this.fileTextUploadList.push(newFile)
    
                this.editor.focus()
    
                this.editor.insertEmbed(this.editor.getSelection().index, 'image', this.fileTextUploadList[0].url)
    
                this.handleTextRemove()
    
            },
    
            pListChange(list) { //将多个参数存到数组里
    
                this.paramsList = list
    
            },
    
            cListChange(list) {
    
                this.goodcount = list
    
            },
    
            onEditorBlur(editor) {
    
                // console.log('editor blur!')
    
            },
    
            onEditorFocus(editor) {
    
                // console.log('editor focus!')
    
            },
    
            onEditorReady(editor) {
    
                // console.log('editor ready!')
    
            },
    
            getupdatedata(v) { //统一获取值,赋值到页面的输入框内
    
                // console.log("已get到数据",v)
    
                var pn = new URLSearchParams();
    
                pn.append("xcxGoodsId", v);
    
                var _this = this;
    
                axios.get('/getXcxGoodsById.do', {
                    params: pn
                }).then(r => {
                    if (r.data.code == 200) {
                        var zx = r.data.response.xcxGoods
                        _this.f.name = zx.name
                        _this.f.cateId = zx.cateId
                        _this.f.tag = zx.tag
                        _this.plist = JSON.parse(zx.param)
                        if (zx.specCount==null) {
                            var n = {
                                count: '',
                                price:'',
                                oldPrice:'',
                                ptType:'',
                                ptPrice:''
                            }
                            _this.clist.push(n)
                        } else {
                            _this.clist = JSON.parse(zx.specCount)
                            // console.log("_this.clist",_this.clist)//!!!!
                        }
                        _this.f.spec = zx.spec
                        _this.f.price = zx.price
                        _this.f.oldPrice = zx.oldPrice
                        _this.fileDetailUploadList.push({
                            name: '',
                            url: zx.image
                        })
                        _this.fileSmallUploadList.push({
                            name: '',
                            url: zx.thumImage
                        })
                        _this.ra = zx.status
                        _this.f.detail = zx.detail
                        if(zx.ptDeliverytype!=null){
                            _this.ptDeliverytype=zx.ptDeliverytype
                        }else{
                            _this.ptDeliverytype=2
                        }
                        if(zx.deliverytype!=null){
                            _this.deliverytype=zx.deliverytype
                        }else{
                            _this.deliverytype=0
                        }
    
                    } else {
                        if(r.data.message=="not login"&&r.data.code==500){
                            _this.$message.error("访问者,请登录")
                            router.push('/Login');
                            return
                        }    
                        _this.$message(r.data.message)
    
                    }
    
                })
    
            }
    
        },
    
        beforeCreate() { //路由进入的时候判断权限
    
            let _this = this
    
            if (!this.$store.state.shiro) {
    
                _this.$router.push('/full')
    
            }
    
            axios.get('/listXcxGoodsClass.do').then(r => { //获取商品分类
    
                _this.opt = [].concat(r.data.response.xcxGoodsClassList)
    
            })
    
        }
    
    }
</script>
<style>
    .ql-container {
    
        height: 400px !important;
    
    }
    
    
    
    .el-upload-dragger {
    
        height: 160px !important;
    
    }
    
    
    
    .btnpt {
    
        position: relative;
    
        z-index: 200;
    
        top: 48px;
    
        left: 1073px;
    
        background-color: #fff;
    
        border: none;
    
        width: 17px;
    
        orphans: 0;
    
        opacity: 0;
    
    }
</style>

